package edu.hebeu.evil.freshmenguide;

import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.melnykov.fab.FloatingActionButton;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.Types.BoomType;
import com.nightonke.boommenu.Types.ButtonType;
import com.nightonke.boommenu.Types.PlaceType;
import com.nightonke.boommenu.Util;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.recker.flybanner.FlyBanner;

import java.util.ArrayList;
import java.util.List;

import edu.hebeu.evil.freshmenguide.Activity.SchoolViewActivity;
import edu.hebeu.evil.freshmenguide.Activity.WebViewActivity;
import edu.hebeu.evil.freshmenguide.Utils.SuperToast.SuperToast;
import edu.hebeu.evil.freshmenguide.Utils.Utils;

/********************************************
 * 工程名：FreshmenGuide
 * 包名：edu.hebeu.evil.freshmenguide
 * 时间：16-7-4 下午10:28
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：主界面底层，主要用于上拉隐藏，图片轮循，浮动按钮
 ********************************************/
public abstract class BaseActivity extends AppCompatActivity implements ObservableScrollViewCallbacks
{

    public abstract int setContentView();

    public abstract void onCreate();

    private static final float MAX_TEXT_SCALE_DELTA = 0.3f;

    private FlyBanner flyBanner;
    private View overlayView;
    private TextView titleView;
    private BoomMenuButton boomMenuButton;
    private int actionBarSize;
    private int flexibleSpaceShowFabOffset;
    private int flexibleSpaceImageHeight;
    private int fabMargin;
    private boolean fabIsShown;

    protected ObservableScrollView scrollView;

    private int smoothScrollTo = 600;/*缓慢下降控制参数*/

    private boolean init = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(setContentView());
        initView();

        scrollView.setScrollViewCallbacks(this);

        titleView.setText("河北工程大学");
        setTitle(null);

        ViewHelper.setScaleX(boomMenuButton, 0);
        ViewHelper.setScaleY(boomMenuButton, 0);

        ScrollUtils.addOnGlobalLayoutListener(scrollView, new Runnable()
        {
            @Override
            public void run()
            {
                scrollView.scrollTo(0, flexibleSpaceImageHeight - actionBarSize);
                //onScrollChanged(0, false, false);
            }
        });
        slowDown();/*缓慢下降*/
        initLocalBanner();
        onCreate();
    }

    /**
     * 初始化控件
     */
    private void initView()
    {
        flexibleSpaceImageHeight = getResources().getDimensionPixelSize(R.dimen.flexible_space_image_height);
        flexibleSpaceShowFabOffset = getResources().getDimensionPixelSize(R.dimen.flexible_space_show_fab_offset);
        actionBarSize = getActionBarSize();
        fabMargin = getResources().getDimensionPixelSize(R.dimen.margin_standard);

        flyBanner = (FlyBanner) findViewById(R.id.image);
        overlayView = findViewById(R.id.overlay);
        scrollView = (ObservableScrollView) findViewById(R.id.scroll);
        titleView = (TextView) findViewById(R.id.title);
        boomMenuButton = (BoomMenuButton) findViewById(R.id.fab);
    }

    /**
     * 图片轮循，加载本地图片
     */
    private void initLocalBanner()
    {
        List<Integer> images = new ArrayList<>();
        images.add(R.drawable.school1);
        images.add(R.drawable.istime);
        images.add(R.drawable.school1);
        images.add(R.drawable.istime);
        flyBanner.setImages(images);
    }


    /**
     * 浮动按钮事件
     *
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus)
    {
        super.onWindowFocusChanged(hasFocus);

        // Use a param to record whether the boom button has been initialized
        // Because we don't need to init it again when onResume()
        if (init) return;
        init = true;

        Drawable[] subButtonDrawables = new Drawable[3];
        int[] drawablesResource = new int[]{
                R.drawable.leftmenu_about,
                R.drawable.leftmenu_about,
                R.drawable.leftmenu_about
        };
        for (int i = 0; i < 3; i++)
            subButtonDrawables[i] = ContextCompat.getDrawable(this, drawablesResource[i]);

        String[] subButtonTexts = new String[]{"BoomMenuButton", "View source code", "Follow me"};

        int[][] subButtonColors = new int[3][2];
        subButtonColors[0][1] = ContextCompat.getColor(this, R.color.p_cyan);
        subButtonColors[0][0] = Util.getInstance().getPressedColor(subButtonColors[0][1]);
        subButtonColors[1][1] = ContextCompat.getColor(this, R.color.p_lime);
        subButtonColors[1][0] = Util.getInstance().getPressedColor(subButtonColors[1][1]);
        subButtonColors[2][1] = ContextCompat.getColor(this, R.color.p_orange);
        subButtonColors[2][0] = Util.getInstance().getPressedColor(subButtonColors[2][1]);


        new BoomMenuButton.Builder()
                .addSubButton(ContextCompat.getDrawable(this, R.drawable.fab_school), subButtonColors[0], "   报到指南")
                .addSubButton(ContextCompat.getDrawable(this, R.drawable.fab_school), subButtonColors[1], "   助学基金")
                .addSubButton(ContextCompat.getDrawable(this, R.drawable.fab_school), subButtonColors[2], "   校园风景")
                .button(ButtonType.HAM)
                .boom(BoomType.PARABOLA)
                .place(PlaceType.HAM_3_1)
                .subButtonTextColor(ContextCompat.getColor(this, R.color.black))
                .subButtonsShadow(Util.getInstance().dp2px(2), Util.getInstance().dp2px(2))
                .onSubButtonClick(new BoomMenuButton.OnSubButtonClickListener()
                {
                    @Override
                    public void onClick(int buttonIndex)
                    {
                        switch (buttonIndex)
                        {
                            case 0:
                                startActivity(new Intent(BaseActivity.this, WebViewActivity.class)
                                        .putExtra("title", "报到指南").putExtra("url", "file:///android_asset/baodao.html"));
                                break;
                            case 1:
                                SuperToast.buttonToast(BaseActivity.this)
                                        .setText("尚未开启，敬请期待")
                                        .show();
                                break;
                            case 2:
                                startActivity(new Intent(BaseActivity.this, SchoolViewActivity.class));
                                break;
                        }
                    }
                })
                .init(boomMenuButton);
    }

    /**
     * 缓慢下降
     */
    private void slowDown()
    {
        new Utils.SHandler()
        {
            @Override
            public void thread(Handler handler)
            {
                for (int i = 0; i < 120; i++)
                {
                    smoothScrollTo -= 5;
                    handler.sendEmptyMessage(0);
                    Utils.Threadsleep(15);
                }
            }

            @Override
            public void handler()
            {
                scrollView.smoothScrollTo(0, smoothScrollTo);
            }

        }.startByCustom();
    }


    protected int getActionBarSize()
    {
        TypedValue typedValue = new TypedValue();
        int[] textSizeAttr = new int[]{R.attr.actionBarSize};
        int indexOfAttrTextSize = 0;
        TypedArray a = obtainStyledAttributes(typedValue.data, textSizeAttr);
        int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
        a.recycle();
        return actionBarSize;
    }

    /*************************************************************************
     * @param scrollY
     * @param firstScroll
     * @param dragging
     */
    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging)
    {
        // Translate overlay and image
        float flexibleRange = flexibleSpaceImageHeight - actionBarSize;
        int minOverlayTransitionY = actionBarSize - overlayView.getHeight();
        ViewHelper.setTranslationY(overlayView, ScrollUtils.getFloat(-scrollY, minOverlayTransitionY, 0));
        ViewHelper.setTranslationY(flyBanner, ScrollUtils.getFloat(-scrollY / 2, minOverlayTransitionY, 0));

        // Change alpha of overlay
        ViewHelper.setAlpha(overlayView, ScrollUtils.getFloat((float) scrollY / flexibleRange, 0, 1));

        // Scale title text
        float scale = 1 + ScrollUtils.getFloat((flexibleRange - scrollY) / flexibleRange, 0, MAX_TEXT_SCALE_DELTA);
        ViewHelper.setPivotX(titleView, 0);
        ViewHelper.setPivotY(titleView, 0);
        ViewHelper.setScaleX(titleView, scale);
        ViewHelper.setScaleY(titleView, scale);

        // Translate title text
        int maxTitleTranslationY = (int) (flexibleSpaceImageHeight - titleView.getHeight() * scale);
        int titleTranslationY = maxTitleTranslationY - scrollY;
        ViewHelper.setTranslationY(titleView, titleTranslationY);

        // Translate FAB
        int maxFabTranslationY = flexibleSpaceImageHeight - boomMenuButton.getHeight() / 2;
        float fabTranslationY = ScrollUtils.getFloat(
                -scrollY + flexibleSpaceImageHeight - boomMenuButton.getHeight() / 2,
                actionBarSize - boomMenuButton.getHeight() / 2,
                maxFabTranslationY);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
        {
            // On pre-honeycomb, ViewHelper.setTranslationX/Y does not set margin,
            // which causes FAB's OnClickListener not working.
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) boomMenuButton.getLayoutParams();
            lp.leftMargin = overlayView.getWidth() - fabMargin - boomMenuButton.getWidth();
            lp.topMargin = (int) fabTranslationY;
            boomMenuButton.requestLayout();
        }
        else
        {
            ViewHelper.setTranslationX(boomMenuButton, overlayView.getWidth() - fabMargin - boomMenuButton.getWidth());
            ViewHelper.setTranslationY(boomMenuButton, fabTranslationY);
        }

        // Show/hide FAB
        if (fabTranslationY < flexibleSpaceShowFabOffset)
        {
            hideFab();
        }
        else
        {
            showFab();
        }
    }

    @Override
    public void onDownMotionEvent()
    {
    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState)
    {
    }

    private void showFab()
    {
        if (!fabIsShown)
        {
            ViewPropertyAnimator.animate(boomMenuButton).cancel();
            ViewPropertyAnimator.animate(boomMenuButton).scaleX(1).scaleY(1).setDuration(200).start();
            fabIsShown = true;
        }
    }

    private void hideFab()
    {
        if (fabIsShown)
        {
            ViewPropertyAnimator.animate(boomMenuButton).cancel();
            ViewPropertyAnimator.animate(boomMenuButton).scaleX(0).scaleY(0).setDuration(200).start();
            fabIsShown = false;
        }
    }


}
